package com.bluemsun.naturallanguageprocessing.wechat;

import com.alibaba.fastjson.JSONObject;
import com.bluemsun.naturallanguageprocessing.common.ServerResponse;
import com.bluemsun.naturallanguageprocessing.entity.User;
import com.bluemsun.naturallanguageprocessing.entity.UserApi;
import com.bluemsun.naturallanguageprocessing.service.ICollectService;
import com.bluemsun.naturallanguageprocessing.service.IUserService;
import com.bluemsun.naturallanguageprocessing.util.HttpClientUtil;
import com.bluemsun.naturallanguageprocessing.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.bluemsun.naturallanguageprocessing.util.RedisUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@RestController
@RequestMapping("/api")
public class UserWeChatApiController {

    private Logger logger = LoggerFactory.getLogger(UserWeChatApiController.class);
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisUtil redisUtil;
    @Resource
    private ICollectService iCollectService;


    @PostMapping("/login")
    @ResponseBody
    public ServerResponse user_login(
            @RequestParam("code") String code,
            @RequestParam("nickName") String nickName,
            @RequestParam("gender") Integer gender,
            @RequestParam("avatarUrl") String avatarUrl,
            @RequestParam("country") String country,
            @RequestParam("province") String province,
            @RequestParam("city") String city,
            @RequestParam("language") String language,
            HttpServletResponse response
    ){
        //二次登录返回判断值
        // 配置请求参数
        Map<String, String> param = new HashMap<>();
        param.put("appid", UserConstantInterface.WX_LOGIN_APPID);
        param.put("secret", UserConstantInterface.WX_LOGIN_SECRET);
        param.put("js_code", code);
        param.put("grant_type", UserConstantInterface.WX_LOGIN_GRANT_TYPE);
        // 发送请求
        String open_id = null;
        try {
            String wxResult = HttpClientUtil.doGet(UserConstantInterface.WX_LOGIN_URL, param);
            JSONObject jsonObject = JSONObject.parseObject(wxResult);
            // 获取参数返回的
            String session_key = jsonObject.get("session_key").toString();
            open_id = jsonObject.get("openid").toString();
        } catch (Exception exception) {
            exception.printStackTrace();
            logger.error("错误原因",exception);
        }
        // 根据返回的user实体类，判断用户是否是新用户，不是的话，更新最新登录时间，是的话，将用户信息存到数据库
        UserApi user = userService.selectByOpenId(open_id);
        String userInfo=null;
        if(user != null){
            user.setUpdateTime(new Date());
            userService.updateById(user);
            userInfo = UUID.randomUUID().toString();
            //一年有效期
            redisUtil.setEx(userInfo, JsonUtil.obj2String(user),60*60*24*365);
            response.setHeader("token",userInfo);
        }else{
            UserApi insert_user = new UserApi();
            insert_user.setAvatarUrl(avatarUrl);
            insert_user.setNickName(nickName);
            insert_user.setGender(gender);
            insert_user.setCreateTime(new Date());
            insert_user.setUpdateTime(new Date());
            insert_user.setCity(city);
            insert_user.setLanguage(language);
            insert_user.setCountry(country);
            insert_user.setProvince(province);
            insert_user.setOpenId(open_id);
            System.out.println("insert_user:"+insert_user.toString());
            // 添加到数据库
            Integer flag = userService.insert(insert_user);
            if(flag==0){
                return ServerResponse.createByErrorMessage("添加出错");
            }else{
                userInfo = UUID.randomUUID().toString();
                //一年有效期
                redisUtil.setEx(userInfo, JsonUtil.obj2String(insert_user),60*60*24*365);
                response.setHeader("token",userInfo);
            }
            // 为新用户创建默认文件夹
            iCollectService.createFavorite(insert_user.getId(), "默认收藏夹");
        }
        // 封装返回小程序
        return ServerResponse.createBySuccess();
    }
    @GetMapping("/islogin")
    @ResponseBody
    public ServerResponse isLogin(HttpServletRequest request){
        return userService.isLogin(request);
    }

    @PostMapping("/update")
    @ResponseBody
    public ServerResponse update(@RequestBody UserApi user,HttpServletRequest request){
        return userService.updateUser(user,request);
    }

    @PostMapping("/getUserInfo")
    @ResponseBody
    public ServerResponse getUserInfo(HttpServletRequest request){
        UserApi userApi= userService.getUserInfo(request);
        return ServerResponse.createBySuccess("返回对象",userApi);
    }

}
